package top.mcwebsite.playandroid.business.me.impl.main.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.*
import top.mcwebsite.playandroid.business.me.impl.api.MeApiService
import top.mcwebsite.playandroid.business.me.impl.model.CollectionArticleModel
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager
import java.lang.RuntimeException

class CollectionArticleViewModel :
    BaseViewModel<CollectionArticleIntent, CollectionArticleUIState, CollectionArticleUIEffect>(CollectionArticleUIState()) {

    private val homePageNetWorkApi = ServiceManager.getService<NetworkService>()
        .createApi<MeApiService>()

    private val pager = Pager(PagingConfig(pageSize = 10)) {
        HomePageArticlePagingSource()
    }

    val pagerFlow = pager.flow.cachedIn(viewModelScope)

    inner class HomePageArticlePagingSource : PagingSource<Int, CollectionArticleModel>() {
        override fun getRefreshKey(state: PagingState<Int, CollectionArticleModel>): Int? {
            return null
        }

        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CollectionArticleModel> {
            return try {
                val nextPageNumber = params.key ?: 0
                val data = homePageNetWorkApi.collectionArticles(nextPageNumber)
                if (data.errorCode == 0) {
                    LoadResult.Page(
                        data = data.data?.datas ?: emptyList(),
                        prevKey = if (nextPageNumber == 0) null else nextPageNumber - 1,
                        nextKey = if (data.data?.datas.isNullOrEmpty()) null else nextPageNumber + 1
                    )
                } else {
                    LoadResult.Error(RuntimeException("未知错误"))
                }
            } catch (e: Exception) {
                return LoadResult.Error(e)
            }
        }
    }

    override fun handleIntent(intent: CollectionArticleIntent) {
        when (intent) {
            is CollectionArticleIntent.ClickArticleIntent -> {
                sendUiEffect(CollectionArticleUIEffect.GoArticleDetailUIEffect(intent.collectionArticleModel.link))
            }
        }
    }
}